package com.app.couponsharelife.ui.main.home
import android.animation.ObjectAnimator
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.HomeActivityLink
import com.app.couponsharelife.data.bean.HomeClassBean
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.main.home.message.MessageActivity
import com.app.couponsharelife.ui.main.home.search.SearchSelecteActivity
import com.app.couponsharelife.ui.main.home.shopweb.ShopWebActivity
import com.app.couponsharelife.ui.view.ScaleGeneralTitleView
import com.app.couponsharelife.ui.viewfactory.NewHomeFactory
import com.app.couponsharelife.utils.AppUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.newfragment_layout.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import java.util.HashMap

/**
 *Created by xct on 2018/12/20
 *Description:首页
 */
class NewHomeFragment:LazyFragment() {
    private var newHomeFactory:NewHomeFactory?=null
    private var commonNavigator:CommonNavigator?=null
    private var classList= arrayListOf<HomeClassBean>()
    private var animType=false
    private var activityLinkUrl=""
    companion object {
        fun newInstance(): NewHomeFragment {
            val fragment = NewHomeFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.newfragment_layout

    override fun initViews() {
        newHomeFactory=NewHomeFactory()
        getData()
        getLink()
        newhomefrag_lltitle.post {
            val layoutparams=newhomefrag_lltitle.layoutParams as ConstraintLayout.LayoutParams
            layoutparams.width= AppUtils.getDisplayMetrics(context!!).widthPixels
            layoutparams.height= AppUtils.getStatusBarHeight(activity!!)
            newhomefrag_lltitle.layoutParams=layoutparams
        }
        newhomefrag_llsearch.setOnClickListener {
            val intent=Intent(activity, SearchSelecteActivity::class.java)
            intent.putExtra("Type",0)
            startActivity(intent)
        }
        newhomefrag_rlmessage.setOnClickListener {
            startActivity(Intent(activity,MessageActivity::class.java))
            //startActivity(Intent(activity,ShopOrderActivity::class.java))
        }
        newhomefrag_activityBut.setOnClickListener {
            if (activityLinkUrl.isNotEmpty()) {
                val intent = Intent(activity, ShopWebActivity::class.java)
                intent.putExtra("url", activityLinkUrl)
                startActivity(intent)
            }else{
                showToastMsg("数据出错，请稍后再试！")
            }
        }
    }

    override fun lazyLoad() {

    }

    private fun setViewPager(){
        newhomefrag_viewpager.offscreenPageLimit=6
        newhomefrag_viewpager.adapter=object :FragmentPagerAdapter(childFragmentManager){
            override fun getItem(position: Int): Fragment {
                return newHomeFactory!!.createFragment(position,classList[position])
            }

            override fun getCount(): Int {
                return classList.size
            }

            override fun getPageTitle(position: Int): CharSequence? {
                return classList[position].name
            }
        }
        newhomefrag_viewpager.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                if (position==0){
                    newhomefrag_topbg.visibility=View.VISIBLE
                    newhomefrag_bgtop.visibility=View.INVISIBLE
                }/*else{
                    newhomefrag_topbg.visibility=View.INVISIBLE
                    newhomefrag_bgtop.visibility=View.VISIBLE
                    val homeClassBean=classList[position]
                    *//*Glide.with(this@NewHomeFragment).asBitmap()
                            .apply(RequestOptions().error(R.drawable.home_default_bg).placeholder(R.drawable.home_default_bg))
                            .load(Contacts.APP_LIFE_IMGURL+homeClassBean.bgImg)
                            .into(newhomefrag_bgtop)*//*
                }*/
            }
        })
        commonNavigator= CommonNavigator(activity)
        commonNavigator!!.adapter=object : CommonNavigatorAdapter(){
            override fun getTitleView(p0: Context, p1: Int): IPagerTitleView {
                val colorTransitionPagerTitleView= ScaleGeneralTitleView(p0)
                colorTransitionPagerTitleView.normalColor = resources.getColor(R.color.white)
                colorTransitionPagerTitleView.textSize=18f
                colorTransitionPagerTitleView.selectedColor = resources.getColor(R.color.white)
                colorTransitionPagerTitleView.text = classList[p1].name
                colorTransitionPagerTitleView.setOnClickListener { newhomefrag_viewpager.currentItem = p1 }
                return colorTransitionPagerTitleView
            }

            override fun getCount(): Int {
                return classList.size
            }

            override fun getIndicator(p0: Context?): IPagerIndicator? {
                /*val indicator=LinePagerIndicator(p0)
                indicator.setColors(resources.getColor(R.color.act_main_bot_nav_select_text_color))*/
                return null
            }
        }
        newhomefrag_tablayout.navigator=commonNavigator
        /*val titleContainer = commonNavigator!!.titleContainer // must after setNavigator
        titleContainer.showDividers = LinearLayout.SHOW_DIVIDER_MIDDLE*/
        //titleContainer.dividerPadding = UIUtil.dip2px(context, 5.0)
        ViewPagerHelper.bind(newhomefrag_tablayout, newhomefrag_viewpager)
    }
    private fun getData(){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        RetrofitWorker.retrofitWorker.getNewHomeClass(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<List<HomeClassBean>>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<List<HomeClassBean>>) {
                        dismissProgressDialog()
                        if (it.code==200){
                            if (it.data!!.isNotEmpty()){
                                classList.clear()
                                /*val myHomeClassBean=HomeClassBean()
                                myHomeClassBean.name="精选"
                                classList.add(myHomeClassBean)*/
                                classList.addAll(it.data!!)
                                setViewPager()
                                getLink()
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private fun getLink(){
        val map= HashMap<String,String>()
        RetrofitWorker.retrofitWorker.getAlipayLink(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<HomeActivityLink>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<HomeActivityLink>) {
                        if (200==it.code){
                            if (it.data!=null){
                                activityLinkUrl=it.data!!.link?:""
                                Glide.with(context!!).asBitmap()
                                        .apply(RequestOptions().circleCrop()
                                                .placeholder(R.drawable.ic_tribe_boy_thumb)
                                                .error(R.drawable.ic_tribe_boy_thumb))
                                        .load(Contacts.REMOTE_IMAGE_URL +it.data!!.image_url?:"")
                                        .into(newhomefrag_activityBut)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {

                    }
                })
    }
    fun visibilityAnim(){
        if (!animType){
            return
        }
        val mAnimatorA = ObjectAnimator.ofFloat(newhomefrag_activityBut, View.TRANSLATION_X, 120f, 0f).setDuration(500)
        mAnimatorA.start()
        animType=false
    }
    fun goneAnim(){
        if (animType){
            return
        }
        val mAnimatorA = ObjectAnimator.ofFloat(newhomefrag_activityBut, View.TRANSLATION_X, 0f, 120f).setDuration(500)
        mAnimatorA.start()
        animType=true
    }
}